package com.ysm.smfu.chat;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ysm.smfu.R;
import com.ysm.smfu.activity.BaseActivity;
import com.ysm.smfu.bean.Friend;
import com.ysm.smfu.manager.GlideCircleTransform;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ThreadUtils;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import chatuidemo.db.DBManager;

/**
 * Created by Administrator on 2016/10/27.
 */
public class ShenqingFriendActivity extends BaseActivity {
    @BindView(R.id.list)
    ListView list;
    @BindView(R.id.title_body)
    TextView titleBody;
    @BindView(R.id.mainActivity_topbar_img)
    ImageView mainActivityTopbarImg;
    private MyAdapter myadapter;
    private List<Friend> has = new ArrayList<>();
    private List<Friend> no = new ArrayList<>();
    private Map<String, List<Friend>> map;

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.em_activity_new_friends_msg);
        ButterKnife.bind(this);
        titleBody.setText("好友申请");
        mainActivityTopbarImg.setVisibility(View.GONE);
        getDateConfig();
    }

    /**
     * 获取申请联系人数据
     */
    private void getDateConfig() {
        ThreadUtils.runOnBackThread(new Runnable() {
            @Override
            public void run() {
                map = DBManager.getInstance().getShenqingContact();
                has = map.get("has");
                no = map.get("no");
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (myadapter == null) {
                            myadapter = new MyAdapter();
                            list.setAdapter(myadapter);
                        }
                    }
                });
            }
        });
    }

    class MyAdapter extends BaseAdapter {

        private Friend noFriend;
        private Friend hasFriend;

        @Override
        public int getCount() {
            return has.size() + no.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = UIUtils.inflate(R.layout.invite_msg);
                viewHolder = new ViewHolder(convertView);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if (position < no.size()) {
                noFriend = no.get(position);
                if (!TextUtils.isEmpty(noFriend.imageAddress) && !noFriend.imageAddress.startsWith("null?")) {
                    Glide.with(ShenqingFriendActivity.this).load(noFriend.imageAddress).placeholder(R.drawable.myimg2).error(R.drawable.myimg2)
                            .transform(new GlideCircleTransform(UIUtils.getContext()))
                            .into(viewHolder.avatar);
                }
                viewHolder.name.setText(noFriend.petName);
                viewHolder.add_defuase.setVisibility(View.VISIBLE);
                viewHolder.hasAdd.setVisibility(View.GONE);
            } else {
                hasFriend = has.get(position - no.size());
                if (!TextUtils.isEmpty(hasFriend.imageAddress) && !hasFriend.imageAddress.startsWith("null?")) {
                    Glide.with(ShenqingFriendActivity.this).load(hasFriend.imageAddress).placeholder(R.drawable.myimg2).error(R.drawable.myimg2)
                            .transform(new GlideCircleTransform(UIUtils.getContext()))
                            .into(viewHolder.avatar);
                }
                viewHolder.name.setText(hasFriend.petName);
                viewHolder.add_defuase.setVisibility(View.GONE);
                viewHolder.hasAdd.setVisibility(View.VISIBLE);
            }

//            拒绝添加
            viewHolder.defause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    agreeOrDefauseF(0, noFriend, position);
                }
            });
//            同意添加
            viewHolder.agree.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    agreeOrDefauseF(1, noFriend, position);
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        public ImageView avatar;
        public TextView name;
        public Button defause;
        public Button agree;
        public AutoLinearLayout add_defuase;
        public TextView hasAdd;

        public ViewHolder(View view) {
            add_defuase = (AutoLinearLayout) view.findViewById(R.id.add_defuase);
            avatar = (ImageView) view.findViewById(R.id.avatar);
            name = (TextView) view.findViewById(R.id.name);
            defause = (Button) view.findViewById(R.id.defause);
            agree = (Button) view.findViewById(R.id.agree);
            hasAdd = (TextView) view.findViewById(R.id.hasAdd);
            view.setTag(this);
        }
    }

    /**
     * 添加或拒绝
     * id: 用户id
     * firendId :好友id   state  1 同意，0  忽略
     */
    private void agreeOrDefauseF(final int state, final Friend firend, final int position) {
        BaseProtocal.builder(true).agreeOrDefauseF(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("同意添加好友", response);
//                点击添加或者忽略之后，将此条消息置为已处理，添加到已处理消息集合第一条，刷新adapter重新排序
                if (state == 1) {
                    String state1 = JsonUtil.getState(response);
                    if (TextUtils.equals(state1, "1")) {
//                        更新为已添加
                        DBManager.getInstance().updateShenqingContact(firend.id);
                        DBManager.getInstance().saveContact2(firend);
                        Friend remove = no.remove(position);
                        has.add(remove);
                    } else {
                        ToastUtils.showToast(JsonUtil.getMessage(response));
                    }
                } else {
                    DBManager.getInstance().deleteShenqingContact(firend.id);
                    no.remove(position);
                }
                Intent intent = new Intent();
                intent.putExtra("unCount", no.size());
                setResult(101, intent);
                finish();
                myadapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
            }
        }, state, firend.id);
    }
}
